import React, {forwardRef} from 'react';
import Autosizer from 'react-virtualized-auto-sizer';

import Pologram from 'pologram';

import useNavigator from './useNavigator';

import makeRow from './Row';

import 'pologram/dist/index.modern.css';
import './index.css';

function randomSelect(list) {
  if (list.length === 0) {
    return undefined;
  } else {
    const randIndex = Math.floor(Math.random() * list.length);
    return list[randIndex];
  }
}

class Accrual {
  constructor(cr, dr) {
    this.cr = cr;
    this.dr = dr;
  }
}

class Entry {
  constructor(line, code) {
    this.line = line;
    this.code = code;
    this.lines = [0];
    this.accrual = new Accrual();
    this.succ = [];
  }

  move(entry) {
    entry.succ.push(this);
  }
}


const itemData = [];

for (let i = 0; i < 100000; i++) {
  const newEntry = new Entry(i, Math.random().toString(36).slice(3, 7));

  let list = itemData, curr;

  while (Math.random() > 0.1 && list.length > 0) {
    curr = randomSelect(list);
    list = curr.succ;
  }

  newEntry.code = `${curr?.code ? `${curr.code}.` :''}${newEntry.code}`;
  list.push(newEntry);
}

const History = forwardRef(({children}, ref) => {

  const style = {
    height:'100%',
    alignItems:'center',
    fontWeight: 300,
    backgroundColor: '#ABABAB',
    borderBottom: '1px solid black',
    position: 'sticky',
    top: 0,
  }

  return <div style={style} ref={ref}>
    {children}
  </div>
})

const App = () => {

  const {history, sublist, enter, leave} = useNavigator(itemData);

  const Row = makeRow({enter});
  const HistRow = makeRow({leave});

  const historyWidget = <History>
    {history.map((hist, index, data) => <HistRow {...{key:index, index, data}} />)}
  </History>

  const pologram = ({height}) => <Pologram {...{
    itemData:  sublist,
    rowRenderer: Row, 
    topWidgetRenderer: historyWidget,
    buffer: 50,
    height,
  }} />


  return <div className='wrapper'>
    <div className="h1" >Rendering millions of records with no delay.</div>
    <div style={{flex: '1 1 auto', width: '800px'}}>
      <Autosizer disableWidth={true}>
        {pologram}
      </Autosizer>
    </div>
    <div style={{flex: '0 1 80px', verticalAlign: 'center', padding: '5px 0', width: 800, lineHeight: 1.7, letterSpacing: '-0.04rem'}}>
      With windowing technique, you can load all entry data at one time, but render only a portion of rows, which saves the time of first-screen rendering.
      By scrolling back and forth, the rows moving to the viewport will be rendered on-the-fly. Moreover, 
      the row height can be varied, and position of affected rows will be re-calculated. Feel it.
    </div>
  </div>
}

export default App;
